const express = require("express");
const fs = require("fs");
const marked = require("marked");
const app = express();
const port = 8080;

app.set("view engine", "ejs");
app.set("views", __dirname + "/views");

app.get("/", (req, res) => {
  const articleList = JSON.parse(fs.readFileSync("./articles.json").toString());
  const list = articleList.filter(item => item.state != 1);
  res.render("index", {
    articles: list,
    currentPage: "/",
    useNav: true,
  });
});

app.get("/about", (req, res) => {
  const aboutMarkdownContent = fs.readFileSync("./public/about.md").toString();

  const aboutContent = marked.parse(aboutMarkdownContent);
  res.render("about", {
    articleContent: aboutContent,
    currentPage: "/about",
    useNav: true,
  });
});

app.get("/article/:id", (req, res) => {
  const id = req.params.id;
  const articleList = JSON.parse(fs.readFileSync("./articles.json").toString());
  const targetArticle = articleList.find((i) => i.markdown == id);
  const content = fs
    .readFileSync("./articles/" + targetArticle.markdown)
    .toString();
  res.render("article", {
    articleContent: marked.parse(content),
    image: targetArticle.image,
    currentPage: "/",
    useNav: false,
  });
});

app.use("/public", express.static("public"));

app.listen(port, () => {
  console.log(`muran.me started！`);
});
